import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import type { loginFormData, loginResponseData, Infodata, RegisterResponseData } from '@/api/user/type'   //引入数据类型
import { reqLogin, reqUserInfo, reqLogout, reqregister } from '@/api/user'


export const useUserStore = defineStore('User', () => {
  const token = ref(GET_TOKEN()) //用户唯一标识token
  const username = ref('')
  const avatar = ref('')
  //用户登录的方法
  const userLogin = async (data: loginFormData) => {
    //登录请求
    const result: loginResponseData= await reqLogin(data);
   
    
    //登录请求:成功200->token
    //登录请求:失败201->登录失败错误的信息
    if (result.status == 0) {
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      //console.log(result.token );
      
      token.value = result.token 
      //本地存储持久化存储一份
      SET_TOKEN(result.token)
      //能保证当前async函数返回一个成功的promise
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }
  
  //用户注册的方法
  const userregister = async (data: loginFormData) => {
    //登录请求
    const result: RegisterResponseData = await reqregister(data);

    if (result.status == 0) {
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }
  //获取用户信息方法
  const userInfo = async () => {
    //获取用户信息进行存储仓库当中[用户头像、名字]
    const result:Infodata = await reqUserInfo()
    //如果获取用户信息成功，存储一下用户信息
    if (result.status == 0) {
      username.value = result.data.username
      avatar.value = import.meta.env.VITE_APP_BASE_API  + result.data.avatar
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }


  //退出登录
  const userLogout = async () => {
    //退出登录请求
    const result: RegisterResponseData = await reqLogout()
    if (result.status == 0) {
      //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
      token.value = ''
      username.value = ''
      avatar.value = ''
      REMOVE_TOKEN()
      return 'ok'
    } else {
      return Promise.reject(new Error(result.message))
    }
  }
  return {
    avatar,
    username,
    token,
    userregister,
    userLogin,
    userInfo,
    userLogout
  }
})
